package com.xixisleep.yeapiclientsdk.client;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.xixisleep.yeapiclientsdk.model.User;

import java.util.HashMap;
import java.util.Map;

import static com.xixisleep.yeapiclientsdk.utils.SignUtils.generateSign;


/**
 * 调用第三方接口的客户端
 *
 * @author xixisleep
 */
public class YeApiClient {

    public static final String GATEWAY_HOST = "http://localhost:6680";

    private String accessKey;

    private String secretKey;

    public YeApiClient(String accessKey, String secretKey) {
        this.accessKey = accessKey;
        this.secretKey = secretKey;
    }

    public String getNameByGet(String name){
        //可以单独传入http参数，这样参数会自动做URL编码，拼接在URL中
        HashMap<String, Object> paramMap = new HashMap<>();
        //将”name"参数添加到映射中
        paramMap.put("name", name);
        //使用HttpUtil工具发起GET请求，并获得服务器返回的结果
        String result= HttpUtil.get(GATEWAY_HOST+"/api/name/getName", paramMap);
        System.out.println(result);
        return result;
    }

    /**
     * 通过POST请求获取用户名
     * @param user
     * @return
     */
    public String getUserNameByPost(User user){
        String json = JSONUtil.toJsonStr(user);
        HttpResponse httpResponse = HttpRequest.post(GATEWAY_HOST+"/api/name/username")
                //添加前面构造的请求头
                .addHeaders(getHeaderMap(json))
                .body(json)
                .execute();
        System.out.println(httpResponse.getStatus());
        String result = httpResponse.body();
        System.out.println(result);
        return result;
    }

    public String getNameByPost(String name){
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", name);

        String result= HttpUtil.post(GATEWAY_HOST+"/api/name/postName", paramMap);
        System.out.println(result);
        return result;
    }

    //创建一个私有方法，用于构造请求头
    private Map<String,String> getHeaderMap(String body){
        //创建一个新的 HashMap 对象
        HashMap<String, String> hashMap = new HashMap<>();
        //将“accessKey” 和其对应的值放入map中
        hashMap.put("accessKey",accessKey);
        //注意：不能直接发送密钥
//        hashMap.put("secretKey",secretKey);
        //生成随机数
        hashMap.put("nonce", RandomUtil.randomNumbers(4));
        //请求体内容
        hashMap.put("body",body);
        //当前时间戳
        //String.valueOf() 将数值转换为字符传
        hashMap.put("timestamp",String.valueOf(System.currentTimeMillis() / 1000));
        hashMap.put("sign",generateSign(hashMap,secretKey));
        return hashMap;
    }

}
